<template>
  <div class="main-page" ref="card">
    <Card>
      <div><img :src="img" alt=""></div>
      <div>
        <p class="title">《{{ title }}》</p>
      </div>
      <Viewer :value="value" :plugins="plugins"></Viewer>
    </Card>
  </div>
</template>

<script lang="ts" setup>
import Card from '@/components/Card/Card.vue'
import { ref } from 'vue'

import { Viewer } from '@bytemd/vue-next'
import 'juejin-markdown-themes/dist/juejin.min.css'
import 'bytemd/dist/index.css'
import breaks from '@bytemd/plugin-breaks'
import gemoji from '@bytemd/plugin-gemoji'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight'
import math from '@bytemd/plugin-math-ssr'
import medium from '@bytemd/plugin-medium-zoom'
import mermaid from '@bytemd/plugin-mermaid'
import frontmatter from '@bytemd/plugin-frontmatter'

let value = ref('loading')
let plugins = [breaks(), gemoji(), gfm(), highlight(), math(), medium(), mermaid(), frontmatter()]


//---------------------获取文章内容并获取标题
import {onUnmounted} from 'vue'
import { useRoute, LocationQueryValue } from 'vue-router'
import { useGetArticle } from './hooks/getArticle'
import { useTitlesStore } from '@/store/titlesStore'
import { storeToRefs } from 'pinia'
import { titleItem } from '@/types/titleItem'
import emitter from '@/utils/emitter'
let route = useRoute()
useGetArticle(route.query.id as LocationQueryValue, getValue, getTitles) //获取文章与标题，函数内部向服务器发送请求获取到文章内容后调用getValue回传value
function getTitles(res: titleItem[]) { //获取标题
  const titlesStore = useTitlesStore()
  const { titles } = storeToRefs(titlesStore) //获取titles
  titles.value = res //设置pinia中的title

  emitter.emit('readArticle', true) //挂载完毕，通知开启左侧标题锚点栏
}
interface getArticle {
  content: string,
  title: string,
  img: string
}
let img = ref('#')  //头图
let title = ref('Loading')  //标题
function getValue(res: getArticle) {  //创建回调函数
  value.value = res.content
  img.value = res.img,
  title.value = res.title
}

onUnmounted(() => {
  emitter.emit('readArticle', false)  //article页面卸载，通知关闭左侧标题锚点栏
})


</script>

<style lang="scss" scoped>
.title {
  font-size: $title-size;
  text-align: center;
}

img {
  height: 10rem;
  width: 100%;
  object-fit: cover;
}
</style>